﻿using System;
using System.Threading;
using System.Diagnostics;
using Quartz;

namespace Wexflow.Core
{
    /// <summary>
    /// 定时器 
    /// </summary>
    public class WexflowTimer 
    {
        public TimerCallback TimerCallback { get; set; }
        public object State { get; set; }
        public TimeSpan Period { get; set; }

        bool _doWork;

        public WexflowTimer(TimerCallback timerCallback, object state, TimeSpan period)
        {
            TimerCallback = timerCallback;
            State = state;
            Period = period;

        }



        //只能控制：延迟多久开始执行，每隔多久执行一次，至于执行多少次、
        //什么时间关闭均无法实现，更不用说处理一些复杂的时间间隔了，所以Timer类仅仅适合处理对时间要求非常简单的定时任务。
        public void Start()
        {
            _doWork = true;

            var thread = new Thread(() =>
                {
                    var stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while (_doWork)
                    {
                        if (stopwatch.ElapsedMilliseconds >= Period.TotalMilliseconds)
                        {
                            stopwatch.Reset();
                            stopwatch.Start();
                            TimerCallback.Invoke(State);
                        }
                        Thread.Sleep(100);

                    }

                });

            thread.Start();
        }
        public void StartQuartz()
        {
            _doWork = true;

            var thread = new Thread(() =>
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                while (_doWork)
                {
                    DateTime execute;
                    DateTime current = DateTime.Now;
                    if (DateTime.TryParse(Period.ToString(@"hh\:mm\:ss"), out execute))
                    {
                        //if (stopwatch.ElapsedMilliseconds >= Period.TotalMilliseconds)
                        if (current >= execute)
                        {
                            stopwatch.Reset();
                            stopwatch.Start();
                            TimerCallback.Invoke(State);
                        }
                        Thread.Sleep(100);

                    }
                    else
                    {
                        throw new Exception("WexflowTimer.Start [Period] conversion failed!");
                    }

                }
            });

            thread.Start();
        }

        public void Stop()
        {
            _doWork = false;
        }
    }
}
